<template>
  <el-container style="margin-top: 10px">
    <el-header>
      <el-card style="height: 75px">
        <el-form :inline="true">
          <el-button
            icon="el-icon-plus"
            size="mini"
            type="primary"
            @click="topAddActivity"
          >添加课程</el-button>

          <el-button
            icon="el-icon-plus"
            size="mini"
            type="primary"
          >批量导入
          </el-button>

          <el-form-item label="" style="margin-left: 20px">
            <el-input placeholder="课程名称搜索" size="mini" v-model="courseName"/>
          </el-form-item>

          <el-button
            circle
            type="primary"
            icon="el-icon-search"
            @click="searchClass"
          />
        </el-form>
      </el-card>
    </el-header>

    <el-main>
      <el-card>
        <el-table v-loading="loading" :data="classList">
          <el-table-column align="center" prop="sort" label="排序">
            <template slot-scope="scope">
              <div v-show="!sortShow&& (sortId == scope.row.id) ">
                <el-input size="mini" v-model="scope.row.sort" @blur="sortInputChange(scope.row)"></el-input>
              </div>
              <div @click="sortClick(scope.row)" v-show="sortShow || (sortId != scope.row.id)">
                {{scope.row.sort}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="课程名" align="center" />
          <!-- <el-table-column label="封面图" align="center">
            <template slot-scope="scope">
              <div>
                <img :src="scope.row.avatar" alt="封面图">
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="description" label="课程介绍" />
          <el-table-column align="center" prop="end_date" label="课程周期" />
          <el-table-column align="center" prop="recommend" label="推荐课程">
            <template slot-scope="scope">
              <el-select v-model="scope.row.selectRecom" placeholder="请选择">
                <el-option
                  v-for="item in scope.row.recommend"
                  :key="item.value"
                  size="mini"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column> -->
          <el-table-column width="520px" label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="navto(scope.row.id)"
              >设置子课题</el-button>

              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="hanldePreview(scope.row.id)"
              >修改</el-button>

              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDeleteAdminUser(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>

    <el-footer style="height: 85px">
      <el-card>
        <el-pagination
          style="text-align: center;"
          :current-page="page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </el-footer>
    <!-- 添加 -->
    <el-dialog title="添加课程" :visible.sync="addClassVisible" width="700px" @close="dialogClose">
      <el-form ref="addAdminUserForm" :model="addClassData" :rules="roles">
        <el-form-item label="课程名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="addClassData.name" style="width: 300px" placeholder="请输入课程名称" />
        </el-form-item>
        <!-- <el-form-item label="课程介绍" :label-width="formLabelWidth" prop="description">
          <el-input v-model="addClassData.description" style="width: 300px" placeholder="请输入课程介绍" />
        </el-form-item>
        <el-form-item label="开始时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="addClassData.start_date"
            value-format='yyyy-MM-dd'
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="addClassData.end_date"
            value-format='yyyy-MM-dd'
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="推荐课程" :label-width="formLabelWidth">
          <el-select
            v-model="addClassData.roles_id"
            placeholder="请选择推荐课程"
            style="width: 300px"
          >
            <el-option
              v-for="item in recommendList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="upload_url"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
            :headers="header"
          >
            <img v-if="addClassData.avatar" :src="addClassData.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <span slot="tip" class="el-upload__tip">图片大小不能超过2M</span>
          </el-upload>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addClassVisible = false">取 消</el-button>
        <el-button type="primary" @click="createClass" :disabled="disabled">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { createClass, getClassList, getClassInfo, updateClass, delClass,sortClass } from '@/api/class.js'
import { getToken } from '@/utils/auth'
const baseUrl = process.env.VUE_APP_BASE_API
export default {
  data() {
    return {
      sortShow: true,
      sortId: '',
      disabled: false,
      loading: false,
      courseName: '',
      createOrUpdate: '',
      addClassVisible: false,
      addClassData: {
        start_date: '',
        end_date: '',
        description: '',
        name: '',
        avatar: '',
        sort: 0
      },
      classList: [],
      total: 0,
      page: 1,
      pageSize: 10,
      upload_url: baseUrl + '/admin/user/uploadImage',
      header: {
        Authorization: getToken()
      },
      formLabelWidth: '200px',
      recommendList: [{ 'label': '课程1', 'value': '1' }, { 'label': '课程2', 'value': '2' }, { 'label': '课程3', 'value': '3' }],
      roles: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 1, message: '课程名必须大于1个字', trigger: 'blur' }
        ],
        // description: [
        //   { required: true, message: '请输入课程介绍', trigger: 'blur' },
        //   { min: 20, message: '课程描述必须大于20个字', trigger: 'blur' }
        // ],
        // start_date: [
        //   { required: true, message: '开始时间必填', trigger: 'blur' }
        // ],
        // end_date: [
        //   { required: true, message: '结束时间必填', trigger: 'blur' }
        // ],
        // avatar: [
        //   { required: true, message: '课程图片必填', trigger: 'blur' }
        // ]
      }
    }
  },
  mounted() {
    this.getClassList()
  },
  methods: {
    uploadSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.addClassData.avatar = response.data.url
      } else {
        this.$message.error(response.msg)
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    sortClick(row) {
      this.sortShow = false
      this.sortChangeNum = row.sort
      this.sortId = row.id
    },
    sortInputChange(row) {
      this.sortShow = true
      let obj = {
        course_id: row.id,
        sort: row.sort
      }
      sortClass(obj).then( res => {
        this.$message.success(res.msg)
        this.getClassList()
      })
    },
    topAddActivity() {
      this.addClassVisible = true
      this.createOrUpdate = 'create'
    },
    getClassList() {
      this.loading = true
      const params = {
        course_name: this.courseName,
        page: this.page,
        page_size: this.pageSize
      }
      getClassList(params).then(res => {
        this.classList = res.data.list
        this.total = res.data.paginate.total
        this.loading = false
      }).catch(res => {
        this.loading = false
      })
    },
    searchClass() {
      this.getClassList()
    },
    createClass() {
      this.$refs.addAdminUserForm.validate(valid => {
        if (!valid) {
          return false
        }
        this.disabled = true
        if (this.createOrUpdate=='create') {
          createClass(this.addClassData).then(res => {
            this.$message.success(res.msg)
            this.addClassVisible = false
            this.getClassList()
          }).catch(err => {
            this.addClassVisible = false
          })
        } else{
          //否则就是更新修改
          updateClass(this.addClassData).then(res=>{
            this.$message.success(res.msg)
            this.addClassVisible = false
            this.getClassList()
          }).catch(err => {
            this.addClassVisible = false
          })
        }

      })
    },
    handleUploadImages() {},
    handleSizeChange() {},
    handleCurrentChange(e) {
      this.page = e
      this.getClassList()
    },
    hanldePreview(id) {
      this.addClassVisible = true
      this.createOrUpdate = 'update'
      let obj = { course_id: id }
      getClassInfo(obj).then(res => {
        this.addClassData = res.data
        this.addClassData.course_id = res.data.id
      })
    },
    /**
     * 删除课程
     */
    handleDeleteAdminUser(id) {
      this.$confirm('确认删除,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 如果点击了确定 则执行的逻辑
        delClass({ course_id: id }).then(res => {
          this.$message.success(res.msg)
          this.getClassList()
        })
      })
    },
    dialogClose() {
      this.disabled = false
      this.addClassData = {
        start_date: '',
        end_date: '',
        description: '',
        name: '',
        avatar: '',
        sort: 0
      }
    },
    navto(option) {
      this.$router.push({ path: './class-children?id=' + option })
    }
  }
}
</script>

<style scoped="scoped">
  img{
    width: 100px;
    height: 100px;
  }
  .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
      border-color: #409eff;
  }
  .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
  }
  .avatar {
      object-fit: contain;
      width: 178px;
      height: 178px;
      display: block;
  }
</style>
